#!/bin/bash
SCRIPT=$(readlink -f $0)
CWD=$(dirname ${SCRIPT})
LOG_FILE="/var/log/create_k8suser.log"
USER=$1

function gencert() {
    openssl genrsa -out ${CWD}/${USER}-pki/${USER}.key 2048
    openssl req -new -key ${CWD}/${USER}-pki/${USER}.key -out ${CWD}/${USER}-pki/${USER}.csr -subj "/CN=${USER}"
    openssl x509 -req -in ${CWD}/${USER}-pki/${USER}.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out ${CWD}/${USER}-pki/${USER}.crt -days 365
    openssl x509 -in ${CWD}/${USER}-pki/${USER}.crt --noout --enddate
}

function create_user() {
    kubectl config set-credentials ${USER} --client-certificate=${CWD}/${USER}-pki/${USER}.crt --client-key=${CWD}/${USER}-pki/${USER}.key --embed-certs=true
    kubectl config get-users
}

function log() {
    msg=$*
    DATE=$(date +'%Y-%m-%d %H:%M:%S')
    echo "${DATE} ${msg}" >> ${LOG_FILE}
}

function SafeExec() {
    local cmd=$1
    echo -n "Execing the step [${cmd}]..."
    log "Execing the step [${cmd}]..."
    ${cmd} >>${LOG_FILE} 2>&1
    if [ $? -eq 0 ];then
        echo -n "OK." && echo ""
        log "Exec the step [${cmd}] OK."
    else
        echo -n "Error!" && echo ""
        log "Exec the function [${cmd}] Error!"
        exit 1
    fi
}

function main() {

    if [ ! -d ${CWD}/${USER}-pki ];then
        mkdir ${CWD}/${USER}-pki
    fi

    SafeExec gencert
    SafeExec create_user
}

main
